package api

import (
	"fmt"
	// "reflect"
	// "strings"
	"sync"

	// "gitee.com/kobeyyf/apibox/handler"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/mattn/go-sqlite3"
	"xorm.io/xorm"
)

type RWLockEngine struct {
	*xorm.Engine
	mut *sync.Mutex
}

func NewRWLockEngine(engine *xorm.Engine) *RWLockEngine {
	return &RWLockEngine{Engine: engine, mut: new(sync.Mutex)}
}

func (engine *RWLockEngine) GetXormEngine() *xorm.Engine {
	return engine.Engine
}

func (engine *RWLockEngine) Query(sqlOrArgs ...interface{}) ([]map[string][]byte, error) {
	engine.mut.Lock()
	defer engine.mut.Unlock()
	return engine.Engine.Query(sqlOrArgs)
}

func (engine *RWLockEngine) Inseart(beans ...interface{}) (int64, error) {
	engine.mut.Lock()
	defer engine.mut.Unlock()
	return engine.Engine.Insert(beans)
}

func (engine *RWLockEngine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
	engine.mut.Lock()
	defer engine.mut.Unlock()
	return engine.Engine.Update(bean, condiBeans)
}

func (api *Api) initDB() error {
	c := api.Config.GetStringMapString("db")
	if c == nil {
		return nil
	}
	alias, has := c["db_alias"]
	if has {
		_, err := api.locadDB(alias)
		return err
	}
	return nil
}

func (app *Api) GetEngine(alias string) (engine *xorm.Engine, err error) {
	engine, has := app.dbs[alias]
	if has {
		return engine, nil
	}
	return app.locadDB(alias)
}

func (app *Api) locadDB(alias string) (engine *xorm.Engine, err error) {
	c := app.Config.GetStringMapString(alias)
	if c == nil {
		return nil, fmt.Errorf("DB Alias '%s' Not Exist", alias)
	}
	dbType := c["db_type"]
	dsn := c["data_source_name"]
	if dsn == "" {
		return nil, fmt.Errorf("Init DB Failed, Need Config data_source_name")
	}
	if dbType != "sqlite3" && dbType != "mysql" {
		return nil, fmt.Errorf("Unsupport db_type '%s'. currently support mysql,sqlite3", dbType)

	}

	engine, err = xorm.NewEngine(dbType, dsn)
	if err != nil {
		return nil, err
	}
	app.dbs[alias] = engine
	return engine, nil
}

func (api *Api) List() {

}
